package com.orchid.community.models.controller;

import com.orchid.community.common.utils.CodeEnum;
import com.orchid.community.common.utils.MsgResponse;
import com.orchid.community.common.utils.ResultUtils;
import com.orchid.community.models.DTO.UserParam;
import com.orchid.community.models.entity.SysUsers;
import com.orchid.community.models.service.SysUsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/sysUser")
public class SysUsersController {

    @Autowired
    private SysUsersService sysUsersService;

    @PostMapping("/login")
    public MsgResponse login(@RequestBody SysUsers user) {
        String username = user.getUsername();
        String password = user.getPassword();
        // 参数校验
        if(username.isEmpty() || password.isEmpty()){
            return ResultUtils.fail(CodeEnum.DATA_ERROR);
        }
        return sysUsersService.login(user);
    }

    @PostMapping("/logout")
    public MsgResponse logout(@RequestBody UserParam userParam){
        String sysUserId = userParam.getSysUserId();
        if(sysUserId == null || sysUserId.isEmpty()){
            return ResultUtils.fail("用户id能为空");
        }
        Integer id = Integer.valueOf(sysUserId);
        //清除数据库中用户的token
        return sysUsersService.deleteTokenById(id);
    }

}
